<template>
  <div>
        <Card>
            <div slot="title" style="display: flex; justify-content: flex-end">
                <div>
                    <Tooltip content="新增标签">
                        <Button type="warning" @click="addModal=true" style=" margin-left: 8px"><Icon type="plus"></Icon> </Button>
                    </Tooltip>
                    <Tooltip content="排序和过滤后的数据">
                        <Button type="primary" @click="exportData(2)"><Icon type="funnel"></Icon> </Button>
                    </Tooltip>
                    <Tooltip content="原始数据">
                        <Button type="primary" @click="exportData(1)"><Icon type="ios-download"></Icon> </Button>
                    </Tooltip>
                </div>
            </div>
            <Table :context="self" :data="tableData" :columns="tableColumns" :loading="tableLoading" stripe ref="table"></Table>
            <div style="margin: 12px;overflow: hidden; font-size: 12px">
                <div style="float: right;">
                    <Page :total="tableCount" :current="1" @on-change="changePage" show-total show-elevator></Page>
                </div>
            </div>
        </Card>
    <Modal
      title="新增设备标签"
      v-model="addModal"
      :mask-closable="false"
      @on-ok="confirmFn('新增')">
      <Form :model="addForm" :label-width="80" ref="addV" :rules="addValidate">
        <Form-item label="标签名称" prop="name">
          <Input v-model="addForm.name" placeholder="请输入" style="width: 360px"></Input>
        </Form-item>
        <Form-item label="标签描述" prop="desc">
          <Input v-model="addForm.desc" placeholder="请输入" type="textarea" :autosize="{minRows: 2,maxRows: 5}"
                 style="width: 360px"></Input>
        </Form-item>
        <Form-item label="标签颜色" class="device-icon" prop="color">
          <ColorPicker v-model="addForm.color" recommend />
        </Form-item>
      </Form>
    </Modal>
    <Modal
      title="编辑设备标签"
      v-model="editModal"
      :mask-closable="false"
      @on-ok="confirmFn('编辑')">
      <Form :model="editForm" :label-width="80" ref="editV" :rules="editValidate">
        <Form-item label="标签" prop="name">
          <Input v-model="editForm.name" placeholder="请输入" style="width: 360px"></Input>
        </Form-item>
        <Form-item label="标签描述" prop="desc">
          <Input v-model="editForm.desc" placeholder="请输入" type="textarea" :autosize="{minRows: 2,maxRows: 5}"
                 style="width: 360px" />
        </Form-item>
        <Form-item label="标签颜色" class="device-icon" style="width:440px;" prop="color">
          <ColorPicker v-model="editForm.color" recommend />
        </Form-item>
      </Form>
    </Modal>
  </div>
</template>

<script>
import { tableColumns } from "./data/tag";

export default {
  name: "Device-type",
  mounted() {
    window.remove = this.remove;
    window.edit = this.edit;
    this.changePage(1);
  },
  data() {
    return {
      tableLoading: false,
      self: this,
      colorList: ["blue", "green", "red", "yellow"],
      addModal: false,
      editModal: false,
      confirmText: "",
      editRowIndex: "",
      confirmTextLong: "",
      currentPage: 1,
      currentTab: 0,
      tableCount: 0,
      addValidate: {
        name: [
          {
            type: "string",
            max: 6,
            required: true,
            message: "标签名不能为空且最长为六个字",
            trigger: "blur"
          }
        ],
        color: [
          {
            type: "string",
            required: true,
            message: "请选择标签颜色",
            trigger: "blur"
          }
        ]
      },
      editValidate: {
        name: [
          {
            type: "string",
            max: 6,
            required: true,
            message: "标签名不能为空且最长为六个字",
            trigger: "blur"
          }
        ],
        color: [
          {
            type: "string",
            required: true,
            message: "请选择标签颜色",
            trigger: "blur"
          }
        ]
      },
      belongDict: ["医疗设备", "科研设备"],
      addForm: {
        name: "",
        desc: "",
        color: ""
      },
      editForm: {
        id: "",
        name: "",
        desc: "",
        color: ""
      },
      tableData: [],
      tableColumns
    };
  },
  methods: {
    async changePage(pageN) {
      this.currentPage = pageN;
      this.tableLoading = true;
      const tmpTable = await this.$getRemoteData(`${this.$mapServer}/equip/services/config/deviceTag/${this.currentTab}/${(this.currentPage - 1) * 10}/10`);
      this.tableData = tmpTable.data.data;
      this.tableCount = parseInt(tmpTable.data.count);
      this.tableLoading = false;
    },
    exportData() {
      this.$refs.table.exportCsv({
        filename: "标签列表",
        original: false,
        columns: this.tableColumns.filter((col, index) => index < 5),
        data: this.tableData.filter((data, index) => {
          return true;
        })
      });
    },
    switchTab(n) {
      this.currentTab = n;
      this.changePage(1);
    },
    edit(n) {
      this.editRowIndex = n;
      this.editModal = true;
      this.editForm = {
        id: this.tableData[n].id,
        name: this.tableData[n].name.toString(),
        remark: this.tableData[n].remark,
        color: '#' + this.tableData[n].color.toString()
      };
    },
    remove(n) {
      this.editRowIndex = n;
      this.confirmFn("删除");
    },
    confirmFn(text) {
      switch (text) {
        case "新增":
          this.$refs["addV"].validate(valid => {
            if (valid) {
              this.confirmTextLong = `${this.addForm.name}${this.addForm.desc?'（'+this.addForm.desc+'）':''}`;
              this.$Modal.confirm({
                title: `确认${text}标签`,
                content: `<p>确认${text}标签:<br><span style="font-weight: bold">${
                  this.confirmTextLong
                }</span> ？</p>`,
                loading: true,
                onOk: ()=>{this.finalConfirmFn(text)},
                onCancel: ()=>{this.cancelFn(text)},
              });
            } else {
              this.$Message.error("请注意需要填写的内容!");
              this.$nextTick(() => {
                this.addModal = true;
              });
            }
          });
          break;
        case "编辑":
          this.$refs["editV"].validate(valid => {
            if (valid) {
              this.confirmTextLong = `${
                this.tableData[this.editRowIndex].name
              }（${this.tableData[this.editRowIndex].desc}）为
${this.editForm.name}（${this.editForm.desc}）`;
              this.$Modal.confirm({
                title: `确认${text}标签`,
                content: `<p>确认${text}标签:<br><span style="font-weight: bold">${
                  this.confirmTextLong
                }</span> ？</p>`,
                loading: true,
                onOk: ()=>{this.finalConfirmFn(text)},
                onCancel: ()=>{this.cancelFn(text)},
              });
            } else {
              this.$Message.error("请注意需要填写的内容!");
              this.$nextTick(() => {
                this.editModal = true;
              });
            }
          });
          break;
        case "删除":
          this.confirmTextLong = `${this.tableData[this.editRowIndex].name}（${
            this.tableData[this.editRowIndex].desc
          }）`;
          this.$Modal.confirm({
            title: `确认${text}标签`,
            content: `<p>确认${text}标签:<br><span style="font-weight: bold">${
              this.confirmTextLong
            }</span> ？</p>`,
            loading: true,
            onOk: ()=>{this.finalConfirmFn(text)},
          });
          break;
      }
    },
    cancelFn(action) {
      this.$Modal.remove();
      switch (action) {
        case "新增":
          this.addModal = true;
          break;
        case "编辑":
          this.editModal = true;
          break;
        case "删除":
          break;
      }
    },
    async finalConfirmFn(action) {
      let result;
      try {
        switch (action) {
          case "新增":
            let tmpAdd = {
              id: Date.parse(new Date()),
              name: this.addForm.name,
              remark: this.addForm.desc,
              color: this.addForm.color.replace('#', '')
            };
            result = await this.$getRemoteData(
              `${this.$mapServer}/equip/services/config/addTag`,
              {
                method: "POST",
                data: tmpAdd
              }
            );
            if (result.data.response_code == "000000") {
              this.$Message.success("新增标签成功");
              this.changePage(this.currentPage);
            } else {
              this.$Message.error("新增标签出错，请检查网络情况");
            }
            this.$Modal.remove();
            break;
          case "编辑":
            let tmpEdit = {
              id: this.editForm.id,
              name: this.editForm.name,
              remark: this.editForm.desc,
              color: this.editForm.color.replace('#', '')
            };
            result = await this.$getRemoteData(
              `${this.$mapServer}/equip/services/config/updateTag`,
              {
                method: "PUT",
                data: tmpEdit
              }
            );
            if (result.status === 200 || result.status === 201) {
              this.$Message.success("编辑标签成功");
              this.changePage(this.currentPage);
            } else {
              this.$Message.error("编辑标签出错，请检查网络情况");
            }
            this.$Modal.remove();
            break;
          case "删除":
            result = await this.$getRemoteData(
              `${this.$mapServer}/equip/services/config/deleteTag/${
                this.tableData[this.editRowIndex].id
              }`,
              {
                method: "DELETE"
              }
            );
            if (result.status === 200) {
              this.$Message.success("删除标签成功");
              this.changePage(this.currentPage);
            } else {
              this.$Message.error("删除标签出错，请检查网络情况");
            }
            this.$Modal.remove();
            break;
        }
      } catch (e) {
        console.error(e);
        this.$Message.error(`${action}标签出错，请检查网络情况`);
        this.$Modal.remove();
      }
    }
  }
};
</script>


<style>
.device-tag-tabs .ivu-icon-ios-circle-filled {
  margin-right: 0 !important;
}

.device-tag-tabs .ivu-tabs-tab:nth-of-type(3) {
  color: #3399ff !important;
}

.device-tag-tabs .ivu-tabs-tab:nth-of-type(4) {
  color: #00cc66 !important;
}

.device-tag-tabs .ivu-tabs-tab:nth-of-type(5) {
  color: #ff3300 !important;
}

.device-tag-tabs .ivu-tabs-tab:nth-of-type(6) {
  color: #ff9900 !important;
}

.ivu-table-tbody .ivu-tooltip-rel,
.ivu-table-tbody .ivu-tooltip {
  width: 100%;
}

.ivu-table-tbody .ivu-tooltip-popper .ivu-tooltip-inner {
  white-space: normal !important;
}

.table-tab button i {
  font-weight: bold;
}

.ivu-table table {
  overflow-x: hidden;
}

textarea.ivu-input {
  font-size: 12px !important;
  padding-top: 6px;
  padding-bottom: 6px;
}

.device-icon .ivu-select-dropdown {
  padding: 5px 12px !important;
}

.device-icon .ivu-select-item-selected,
.ivu-select-item-selected:hover {
  background: #eee !important;
}

.device-icon .ivu-form-item-content {
  display: flex;
  justify-content: space-between;
}

.device-icon .ivu-select-item span {
  width: 32px;
  transform: translateX(16px);
  text-align: center;
}
</style>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.table-tab .ivu-tooltip {
  position: absolute;
  top: 48px;
}

.table-tab button:hover {
  color: #5cadff;
}

.table-tab button {
  padding: 0;
  font-size: 20px;
  color: #657180;
}

.tab-export-icon {
  right: 24px;
}

.tab-add-icon {
  right: 64px;
}

h1,
h2 {
  font-weight: normal;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  /*margin: 0 10px;*/
}

a {
  color: #42b983;
}
</style>
